//
//  JYJTableHeadView.m
//  HappyListen
//
//  Created by 冀永金 on 16/8/29.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJTableHeadView.h"
#import "JYJTAMacro.h"
#import "BaseCollectionView.h"
#import "JYJNetWorkParser.h"
#import "JYJTAMacro.h"
#import "JYJBannerListModel.h"
#import "JYJCycleImageCollectionViewCell.h"
#import "JYJVCOfDiscover.h"
#import "JYJVCOfFeaturedTopThreeDetails.h"
#import "Masonry.h"
@interface JYJTableHeadView ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) BaseCollectionView *collection;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSMutableArray <JYJBannerListModel *>*marrOfCycleImage;
@property (nonatomic, strong) UIPageControl *page;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIImageView *imageOfAnimation;
@end
@implementation JYJTableHeadView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        [self createCycleImage];
        [self createPageController];
        
        [self createAnimation];
        [self handleData];
        
        
    }
    return self;
}
- (void)handleData {
   [JYJNetWorkParser POST:@"http://www.aiyinsitanfm.com/mobile/channel/discovery.jhtml" andBody:@"json=%7B%7D" andBodyStyle:JYJBodyString andHeader:HEADDIC andResponse:JYJJSON andSuccessBlock:^(id result) {
       self.marrOfCycleImage = [NSMutableArray array];
       NSArray *listArray = result[@"data"][@"banner_list"];
       for (NSDictionary *dic in listArray) {
           JYJBannerListModel *model = [JYJBannerListModel modelWithDic:dic];
           [self.marrOfCycleImage addObject:model];
       }
       [self.collection reloadData];
       self.imageOfAnimation.hidden = YES;
       // 加判断  防止数据没来之前定时器启动导致系统崩溃！！！！！
       if (self.marrOfCycleImage.count != 0) {
           [self addTimer];
           
       }else {
           [self removeTimer];
       }
       [self.collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:50] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
       
   } andFailureBlock:^(NSError *error) {
       
   }];
}
- (void)createCycleImage {
    _layout = [[UICollectionViewFlowLayout alloc]init];
    _layout.minimumLineSpacing = 0;
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collection = [[BaseCollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:_layout];
    [self addSubview:_collection];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.pagingEnabled = YES;
    [self.collection registerClass:[JYJCycleImageCollectionViewCell class] forCellWithReuseIdentifier:@"pool"];
    self.collection.showsHorizontalScrollIndicator = NO;
    
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _layout.itemSize = CGSizeMake(SCREEN_WIDTH, 200);
    _collection.frame = self.bounds;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 100;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    self.page.numberOfPages = self.marrOfCycleImage.count;
    return self.marrOfCycleImage.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JYJCycleImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    JYJBannerListModel *model = self.marrOfCycleImage[indexPath.item];
    [cell setListModel:model];
    return cell;
}
// 添加pageController
- (void)createPageController {
    self.page = [[UIPageControl alloc]initWithFrame:CGRectMake(0, self.bounds.size.height - 30, SCREEN_WIDTH, 30)];
    _page.currentPageIndicatorTintColor = [UIColor redColor];
    _page.pageIndicatorTintColor = [UIColor grayColor];
    [self addSubview:_page];
}
//计算当前page的算法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int page = (int) (scrollView.contentOffset.x / SCREEN_WIDTH + .5) % self.marrOfCycleImage.count;
    self.page.currentPage = page;
}
- (void)addTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}
- (void)nextImage {
    //设置当前 indePath
    NSIndexPath *currrentIndexPath = [[self.collection indexPathsForVisibleItems]lastObject];
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currrentIndexPath.item inSection:50];
    [self.collection scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    // 设置下一个滚动的item
    NSInteger nextItem = currentIndexPathReset.item +1;
    NSInteger nextSection = currentIndexPathReset.section;
    if (nextItem==self.marrOfCycleImage.count) {
        // 当item等于轮播图的总个数的时候
        // item等于0, 分区加1
        // 未达到的时候永远在50分区中
        nextItem=0;
        nextSection++;
    }
    //NSLog(@"%ld, %ld", nextItem, nextSection);
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    [self.collection scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
- (void)removeTimer {
    [self.timer invalidate];
    self.timer = nil;
    
}
//  用户将要拖拽时  移除定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeTimer];
}
//  用户完成拖拽 加定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addTimer];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    JYJVCOfDiscover *discover  =  (JYJVCOfDiscover *)self.nextResponder.nextResponder.nextResponder.nextResponder.nextResponder.nextResponder;
    discover.tabBarController.tabBar.hidden = YES;
    discover.hidesBottomBarWhenPushed = YES;
   JYJVCOfFeaturedTopThreeDetails *details = [[JYJVCOfFeaturedTopThreeDetails alloc]init];
    details.cycleImageModel = self.marrOfCycleImage[indexPath.row];
    [discover.navigationController pushViewController:details animated:YES];
    discover.hidesBottomBarWhenPushed = NO;
}
- (void)createAnimation {
    self.imageOfAnimation = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"main_load_0"]];
    self.imageOfAnimation.frame = CGRectMake(SCREEN_WIDTH / 2 - 30, 200, 80, 200);
    [self addSubview:_imageOfAnimation];
    NSMutableArray *marr = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        NSString *imageName = [NSString stringWithFormat:@"main_load_%d",i];
        UIImage *image = [UIImage imageNamed:imageName];
        [marr addObject:image];
    }
    _imageOfAnimation.animationDuration = 1;
    _imageOfAnimation.animationImages  = marr;
    _imageOfAnimation.animationRepeatCount = 0;
    [ _imageOfAnimation startAnimating];

    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
